package com.example.yyy

import android.view.View
import androidx.recyclerview.widget.RecyclerView

/**条目点击接口
 * @param RecyclerView需要监听的母项
 */
open class ItemClickSupport(private val mRecyclerView: RecyclerView) : RecyclerView.OnChildAttachStateChangeListener {

    companion object val KEY: Int = 0x99999999.toInt()
    private lateinit var mOnItemListener:OnItemListenerNew //item点击事件
    private lateinit var mOnItemLongListener:OnItemLongListenerNew//item长按事件

    fun setItemListenerNew(listener:OnItemListenerNew){
        mOnItemListener=listener
    }

    fun setItemLongListenerNew(listener:OnItemLongListenerNew){
        mOnItemLongListener=listener
    }
    //初始化
    init {
        mRecyclerView.setTag(KEY,this)
        // 为RecyclerView设置OnChildAttachStateChangeListener事件监听
        mRecyclerView.addOnChildAttachStateChangeListener(this)
    }

    private val mOnClickListener = View.OnClickListener {
        val holder = mRecyclerView.getChildViewHolder(it)
        mOnItemListener.onItemClick(mRecyclerView,it,holder.adapterPosition)
    }

    private val mOnClickLongListener = View.OnLongClickListener {
        val holder = mRecyclerView.getChildViewHolder(it)
        return@OnLongClickListener mOnItemLongListener.onItemLongClick(mRecyclerView,it,holder.adapterPosition)
    }
    //为RecyclerView移除ItemClickSupport
    inner class RemoveFrom(private val view: RecyclerView){
        init {
            val support: ItemClickSupport = view.getTag(KEY) as ItemClickSupport
            support.detach(view)
        }
    }

    fun detach(view: RecyclerView){
        view.removeOnChildAttachStateChangeListener(this)
        view.setTag(KEY,null)
    }
    //RecyclerView的点击事件监听接口
    interface OnItemListenerNew{
        fun onItemClick(view: RecyclerView,itemView: View, position: Int)
    }
    //RecyclerView的长按事件监听接口
    interface OnItemLongListenerNew{
        fun onItemLongClick(view: RecyclerView,itemView: View, position: Int):Boolean
        }

    override fun onChildViewDetachedFromWindow(view: View) {

    }
    //设置了OnChildAttachStateChangeListener事件监听
    override fun onChildViewAttachedToWindow(view: View) {
        view.setOnClickListener(mOnClickListener)
        view.setOnLongClickListener(mOnClickLongListener)
    }
}

